<?php
namespace Admin\Controller;
use Common\Controller\BackendController;

class TaozhuController extends BackendController
{
    protected $apikey = '60c633e71a0e9916';
    protected $url = 'http://api.taokezhushou.com/api/v1/';

    public function _initialize() {
        parent::_initialize();
        set_time_limit(0);
        $this->assign([
            'apikey' => $this->apikey,
        ]);
    }
    /**
     * 全网
     */
    public function Allnetwork()
    {
        if(IS_POST) {
            $page = I('post.page');
            $p = 1;
            while($p <= $page) {
                $url = $this->url . 'all?app_key='.$this->apikey.'&page='.$p;
                $data = file_get_contents($url);
                $msg = $this->tranfer($data);
                $p++;
            }
            $msg['p'] = $page;
            $this->assign('msg',$msg);
        }

        $this->display();
    }

    /**
     * 2小时
     */
    public function hourSale()
    {
        if(IS_POST) {
            $page = I('post.page');
            $p = 1;
            while($p <= $page) {
                $url = $this->url . 'top_hour?app_key='.$this->apikey.'&page='.$p;
                $data = file_get_contents($url);
                $msg = $this->tranfer($data);
                $p++;
            }
            $msg['p'] = $page;
            $this->assign('msg',$msg);
        }

        $this->display();
    }

    public function tranfer($items)
    {
        $totalcoll = 0;
        $thiscount = 0;

        $items = json_decode($items);
        foreach($items->data as $item) {
            $res =  $this->additem($item);
            if($res>0){
                $totalcoll++;
            }
            $thiscount++;
        }
        return $msg = [
            'msg' => '添加成功',
            'code' => 200,
            'totalcoll' => $totalcoll,
            'thiscount' => $thiscount,
        ];
    }

    public function additem($item)
    {
        $model = D('Items');
        $ret  = $model->taozhushou($item);
        return $ret;

    }
}
